<template>
  <div class="global-search">
    <el-input
        v-model="searchKeyword"
        placeholder="搜索菜单..."
        prefix-icon="el-icon-search"
        size="small"
        class="header-search"
        @focus="handleFocus"
        @input="handleSearch"
        ref="searchInput"
    />

    <!-- 搜索结果下拉框 -->
    <el-card v-show="showDropdown" class="search-dropdown" shadow="always">
      <div v-if="searchResults.length" class="search-results">
        <div
            v-for="item in searchResults"
            :key="item.path"
            class="search-item"
            @click="handleSelect(item)"
        >
          <i :class="item.meta.icon"></i>
          <span>{{ item.meta.title }}</span>
          <span class="path-info">{{ getPathTitle(item) }}</span>
        </div>
      </div>
      <div v-else class="no-result">
        <i class="el-icon-info"></i>
        <span>无匹配结果</span>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'GlobalSearch',
  data() {
    return {
      searchKeyword: '',
      showDropdown: false,
      searchResults: [],
    }
  },
  methods: {
    // 收集所有可搜索的路由
    collectRoutes() {
      // 从 vuex 中获取菜单数据
      const menus = this.$store.state.menus
      return this.flattenRoutes(menus)
    },

    // 将多级路由扁平化
    flattenRoutes(routes, parentPath = '', parentTitle = '') {
      let result = []
      routes.forEach(route => {
        if (route.type === 2) { // 只收集类型为菜单的项
          // 构建完整的路由路径
          const fullPath = parentPath 
            ? `${parentPath}/${route.path}`
            : route.path
          
          result.push({
            path: fullPath,  // 使用完整的路由路径
            meta: {
              title: route.menuName,
              icon: route.icon,
              menuPath: route.path
            },
            parentTitle: parentTitle  // 使用传入的 parentTitle
          })
        }

        if (route.children && route.children.length > 0) {
          // 传递当前菜单的名称作为子菜单的父级标题
          result = result.concat(
            this.flattenRoutes(route.children, route.path, route.menuName)
          )
        }
      })
      return result
    },

    // 处理搜索
    handleSearch() {
      if (!this.searchKeyword) {
        this.searchResults = []
        return
      }

      const allRoutes = this.collectRoutes()
      this.searchResults = allRoutes.filter(route => {
        return route.meta?.title?.toLowerCase().includes(this.searchKeyword.toLowerCase())
      })
    },

    // 处理选择
    handleSelect(item) {
      console.log('选中菜单项:', item)
      this.searchKeyword = ''
      this.showDropdown = false
      if (item.path) {
        try {
          // 使用构建好的完整路径进行跳转
          const routePath = `/main/${item.path}`
          this.$router.push({
            path: routePath,
            replace: true
          }).then(() => {
            // 手动更新菜单的激活项
            const sidebarMenu = this.$parent.$refs.sidebar?.$refs.menu
            if (sidebarMenu) {
              sidebarMenu.activeIndex = routePath
            }
          }).catch(err => {
            console.error('路由跳转失败:', err)
            this.$message.error('页面跳转失败，请检查路由配置')
          })
        } catch (error) {
          console.error('路由跳转失败:', error)
          this.$message.error('页面跳转失败')
        }
      }
    },

    // 获取完整路径标题
    getPathTitle(item) {
      return item.parentTitle ? item.parentTitle : item.meta.title
    },

    // 处理输入框聚焦
    handleFocus() {
      this.showDropdown = true
      this.handleSearch()
    }
  },
  mounted() {
    // 点击外部关闭下拉框
    document.addEventListener('click', (e) => {
      if (!this.$el.contains(e.target)) {
        this.showDropdown = false
      }
    })
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleClickOutside)
  }
}
</script>

<style lang="scss" scoped>
.global-search {
  position: relative;

  .header-search {
    width: 200px;
  }

  .search-dropdown {
    position: absolute;
    top: 40px;
    left: 0;
    width: 350px;
    max-height: 400px;
    overflow-y: auto;
    z-index: 2000;

    .search-results {
      .search-item {
        padding: 8px 12px;
        cursor: pointer;
        display: flex;
        align-items: center;

        &:hover {
          background-color: #f5f7fa;
        }

        i {
          margin-right: 8px;
          font-size: 16px;
          color: #909399;
        }

        .path-info {
          margin-left: auto;
          color: #909399;
          font-size: 12px;
        }
      }
    }

    .no-result {
      padding: 20px;
      text-align: center;
      color: #909399;

      i {
        margin-right: 8px;
      }
    }
  }
}
</style> 